import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import { NestExpressApplication } from '@nestjs/platform-express';
import {
  ClassSerializerInterceptor,
  ValidationPipe,
  VersioningType,
} from '@nestjs/common';
import { LoggingInterceptor } from './common/interceptors/logger.interceptor';
import { ConfigService } from '@nestjs/config';
import { generateDocument } from './common/plugin/swagger';
import { ResponseInterceptor } from './common/interceptors/Response.Interceptor';
import { HttpExceptionFilter } from './common/filters/HttpException.filter';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  // 设置静态文件托管目录
  app.useStaticAssets(process.cwd() + '/public', {
    prefix: '/static',
  });

  // 添加全局中间件
  // app.use((req, res, next) => {
  //   console.log('Middleware executed');
  //   next();
  // });
  app.useGlobalInterceptors(new LoggingInterceptor());
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new HttpExceptionFilter()); // 注册异常过滤器
  app.useGlobalInterceptors(
    new ResponseInterceptor(),
    new ClassSerializerInterceptor(app.get(Reflector)),
  );

  const configService = app.get(ConfigService);
  const config = configService.get('common');

  // enable versioning control
  app.enableVersioning({
    type: VersioningType.URI,
    defaultVersion: '1',
  });
  // enable session control
  app.use(
    session({
      secret: config.secret,
      rolling: true,
      resave: true,
      saveUninitialized: true,
      name: `${config.secret}.sid`,
      cookie: {
        httpOnly: true,
        maxAge: config.cookie_maxAge,
      },
    }),
  );
  // 创建swagger文档
  generateDocument(app);
  await app.listen(config.port);
  console.log(`server running on ${await app.getUrl()}`);
  console.log(`swagger ${await app.getUrl()}/doc/api#/`);
}
bootstrap();
